package com.quanlei.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.array;
import android.R.color;
import android.app.Activity;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.quanlei.R;
import com.quanlei.tools.DoubanUtil;

public class DoubanMusicActivity extends Activity {
	/** Called when the activity is first created. */

	TextView stopButton = null;
	TextView playButton = null;
	TextView nextButton = null;
	TextView resetButton = null;
	TextView musicName = null;
	TextView musicDurationTime = null;
	TextView musicCurrentTime = null;
	MediaPlayer mp = new MediaPlayer();
	String[] musics = null;
	JSONArray arrays = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// // UI初始化
		musicDurationTime = (TextView) findViewById(R.id.musicDurationTime);
		TextPaint tp = musicDurationTime.getPaint();
		tp.setFakeBoldText(true);

		musicCurrentTime = (TextView) findViewById(R.id.musicCurrentTime);
		TextPaint ctp = musicCurrentTime.getPaint();
		ctp.setFakeBoldText(true);

		playButton = (TextView) findViewById(R.id.playButton);
		playButton.setOnClickListener(new PlayButtonClickListener());

		stopButton = (TextView) findViewById(R.id.stopButton);
		stopButton.setOnClickListener(new StopButtonClickListener());

		resetButton = (TextView) findViewById(R.id.resetButton);
		resetButton.setOnClickListener(new ResetButtonLisntener());

		musicName = (TextView) findViewById(R.id.musicName);

		initMusicList();
	}

	Handler updateHandler = new Handler() {
		public void handleMessage(Message msg) {
			System.out.println(msg.arg1);
			int tmins = msg.arg1 / 60000;
			int tsecs = msg.arg1 % 60;
			String mins = "";
			String secs = "";
			secs = tsecs < 10 ? "0" + tsecs : tsecs + "";
			if (tmins > 10) {
				mins = tmins + "";
			} else {
				mins = "0" + tmins;
			}
			System.out.println(mins + ":" + secs);
			musicCurrentTime.setText(mins + ":" + secs);
			updateHandler.post(updateThread);
		}
	};

	Runnable updateThread = new Runnable() {

		int i = 0;

		@Override
		public void run() {

			Message msg = updateHandler.obtainMessage();
			i = mp.getCurrentPosition();
			try {
				Thread.sleep(1000);
			} catch (Exception e) {

			}
			if (i == mp.getDuration()) {
				updateHandler.removeCallbacks(updateThread);
			}
			msg.arg1 = i + 1000;
			updateHandler.sendMessage(msg);
		}
	};
	
	class MyHandler extends Handler{
		public MyHandler(){
			
		}
		public MyHandler(Looper looper){
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {
			Bundle b = msg.getData();
			int time = b.getInt("currentTime");
			System.out.println("handlerMessage");
		}
	}

	class PlayButtonClickListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			updateHandler.post(updateThread);
			startOrStopMP();
		}
	}

	class StopButtonClickListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			startOrStopMP();
		}

	}

	class ResetButtonLisntener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			// 初始化MP及界面状态
			mp.stop();
			mp.reset();
			playButton.setVisibility(View.VISIBLE);
			stopButton.setVisibility(View.GONE);
			musicDurationTime.setText("00:00");

			TextView loading = (TextView) findViewById(R.id.loading);
			loading.setVisibility(View.VISIBLE);
			resetButton.setEnabled(false);
			resetButton.setBackgroundResource(R.drawable.reset_select);
			initMusicList();
			resetButton.setEnabled(true);
			resetButton.setBackgroundResource(R.drawable.reset);
			loading.setVisibility(View.INVISIBLE);
		}
	}

	class ListItemClickListner implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			System.out.println(parent);
			System.out.println(view);
			System.out.println(position);
			System.out.println(id);
			View v = parent.getChildAt(position);
			try {
				mp.reset();
				Log.i("MP3 URL:",
						arrays.getJSONObject(position).getString("url"));
				Log.i("MP3 TITLE:",
						arrays.getJSONObject(position).getString("title"));
				musicName.setText(arrays.getJSONObject(position).getString(
						"title"));

				mp.setDataSource(arrays.getJSONObject(position).getString("url"));
				mp.prepare();
				mp.start();
				playButton.setVisibility(View.GONE);
				stopButton.setVisibility(View.VISIBLE);

				String mins = "";
				String secs = "";
				int tmins = mp.getDuration() / 60000;
				int tsecs = mp.getDuration() % 60;
				secs = tsecs < 10 ? "0" + tsecs : tsecs + "";
				if (tmins > 10) {
					mins = tmins + "";
				} else {
					mins = "0" + tmins;
				}
				musicDurationTime.setText(mins + ":" + secs);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void initMusicList() {
		arrays = DoubanUtil.getDoubanMusic();
		if (arrays != null) {
			musics = new String[arrays.length()];
			for (int i = 0; i < arrays.length(); i++) {
				try {
					if (arrays.getJSONObject(i).getString("artist") == null
							|| arrays.getJSONObject(i).getString("artist")
									.equals("")) {
						musics[i] = arrays.getJSONObject(i).getString("title");
					} else {
						musics[i] = arrays.getJSONObject(i).getString("artist")
								+ " - "
								+ arrays.getJSONObject(i).getString("title");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		ListView listView = (ListView) findViewById(R.id.list);
		ListAdapter listAdapter = new ArrayAdapter<String>(
				this.getApplicationContext(), R.layout.musics, musics);

		listView.setClickable(true);
		listView.setOnItemClickListener(new ListItemClickListner());

		listView.setAdapter(listAdapter);
	}

	private void initMusicListUsingSimpleAdapter() {
		arrays = DoubanUtil.getDoubanMusic();
		List<Map<String, String>> list =null;
		if (arrays != null) {
			list = new ArrayList<Map<String, String>>();
			for (int i = 0; i < arrays.length(); i++) {
				try {
					Map<String, String> map = new HashMap<String, String>();
					map.put("artist",
							arrays.getJSONObject(i).getString("artist"));
					map.put("title", arrays.getJSONObject(i).getString("title"));
					list.add(map);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}

		Log.i("Muisc List：", list.size() + "");

		ListView listView = (ListView) findViewById(R.id.list);
		//listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		SimpleAdapter listAdapter = new SimpleAdapter(
				this.getApplicationContext(), list, R.layout.musiclist,
				new String[] { "artist", "title" }, new int[] { R.id.artist,
						R.id.title });

		listView.setClickable(true);
		listView.setOnItemClickListener(new ListItemClickListner());

		listView.setAdapter(listAdapter);
	}

	private void startOrStopMP() {
		if (mp.isPlaying()) {
			mp.pause();
			playButton.setVisibility(View.VISIBLE);
			stopButton.setVisibility(View.GONE);
		} else {
			mp.start();
			playButton.setVisibility(View.GONE);
			stopButton.setVisibility(View.VISIBLE);
		}
	}
}